package wechatUtil

import (
	"encoding/json"
	"errors"
	"fmt"
	"go-api-template/internal/util/httpUtil"
	"go-api-template/service"
)

type Wechat struct {
	accessToken string `json:"access_token"`
}

type GetAccessTokenResp struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	ErrCode     int    `json:"err_code"`
	ErrMsg      string `json:"err_msg"`
}

type SubscribeMessageSendReq struct {
	ToUser     string `json:"touser"`
	TemplateId string `json:"template_id"`
	Data       struct {
		Thing1 struct {
			Value string `json:"value"`
		} `json:"thing1"`
		Thing10 struct {
			Value string `json:"value"`
		} `json:"thing10"`
	} `json:"data"` // 参数和值
	Page             string `json:"page"`
	MiniProgramState string `json:"miniprogram_state"`
	Lang             string `json:"lang"`
}

type SubscribeMessageSendResp struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

func New() (*Wechat, error) {
	var resp GetAccessTokenResp

	bodyStr, err := httpUtil.HttpGet("https://api.weixin.qq.com/cgi-bin/token" +
		"?grant_type=" + "client_credential" +
		"&appid=" + "wx3a3766ca7d3c501a" +
		"&secret=" + "2e886c9e4a9c9989e5c15f4de68e20ba")
	if err != nil {
		service.Log.Sugar().Debugf("%+v", string(bodyStr))
		return nil, err
	}

	err = json.Unmarshal([]byte(bodyStr), &resp)
	if err != nil {
		return nil, err
	}

	if resp.ErrCode != 0 {
		err := errors.New(resp.ErrMsg)
		return nil, err
	}

	return &Wechat{
		accessToken: resp.AccessToken,
	}, nil

}

func (w *Wechat) SubscribeMessageSend(req SubscribeMessageSendReq) error {
	var resp SubscribeMessageSendResp

	reqJson, err := json.Marshal(req)
	if err != nil {
		return err
	}

	url := "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" + "?access_token=" + w.accessToken
	bodyStr, err := httpUtil.HttpPost(url, string(reqJson))

	err = json.Unmarshal([]byte(bodyStr), &resp)
	service.Log.Debug(fmt.Sprintf("%s : %s : %s", url, reqJson, bodyStr))
	if err != nil {
		return err
	}

	return nil
}
